package org.hxzon.demo.juntai.csserver.server;

import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.Selector;

import org.hxzon.project.AppRuntimeException;

public class Util {
    public static String encoding = "UTF-8";

    public static void registerChannel(Selector selector, SelectableChannel channel, int ops, Object attch) {
        try {
            if (channel == null) {
                return; // could happen
            }
            // Set the new channel nonblocking
            channel.configureBlocking(false);
            // Register it with the selector
            channel.register(selector, ops, attch);
        } catch (Exception e) {
            throw AppRuntimeException.rethrow(e);
        }
    }

    public static String readString(ByteBuffer buf) {
        try {
            //buf.flip();//for read
            byte[] dst = new byte[buf.remaining()];
            buf.get(dst);
            return new String(dst, encoding);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void putString(String str, ByteBuffer buf) {
        try {
            //buf.clear();
            byte[] src = str.getBytes(encoding);
            buf.put(src);
            //buf.filp();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void println(Object msg) {
        System.out.println(msg);
    }

    public static void debug(Object msg) {
        System.err.println(msg);
    }
}
